<template>
<span>
    <template v-for="(e,i) in SPU_OBJ">
        <el-form-item class="inline" :key="i+e+'key'" label="名称">
            <el-input v-model="e.key" @change="inputFinish"></el-input>
        </el-form-item>
        <el-form-item class="inline" :key="i+e+'val'" label="内容">
            <el-input v-model="e.value" @change="inputFinish"></el-input>
        </el-form-item>
        <el-form-item class="inline" :key="i+e+'del'">
            <i class="el-icon-delete" @click="handleDel(i)"></i>
        </el-form-item>
        <br :key="i+'br'">
    </template>
    <el-form-item>
        <el-button type="primary" @click="handleAdd">新增</el-button>
    </el-form-item>
</span>
</template>

<script>
export default {
    name: 'SPU',
    props: {
        cb: Function,
        SPU: {
            type: Object,
        },
        rules: {
            type: [Object, Array],
            default: () => []
        },
    },
    data() {
        return {
            SPU_OBJ: [], //商品信息集合{key:value}
            SPU_rules: this.rules, //商品信息集合验证规则
        }
    },
    components: {},
    methods: {
        handleAdd() {
            this.SPU_OBJ.push({
                key: "",
                value: ""
            })
            this.emit_cb();
        },
        emit_cb() {
            var spu = {};
            this.SPU_OBJ.forEach(e => {
                spu[e.key] = e.value;
            })
            console.log(spu);
            this.$emit("cb", spu);
        },
        handleDel(i) {
            this.SPU_OBJ.splice(i, 1);
            this.emit_cb();
        },
        inputFinish(){
            this.emit_cb();
        }
    },
    watch: {
        SPU: {
            handler(val) {
                if (!val) return;
                if (typeof val!=="object") return;
                this.SPU_OBJ = [];
                for (const key in val) {
                    if (val.hasOwnProperty(key)) {
                        const element = val[key];
                        this.SPU_OBJ.push({
                            key: key,
                            value: element
                        });
                    }
                }
                console.log(val,"----===========");
            },
            immediate: true
        },
        
    },
    computed: {},
    created() {},
    mounted() {},
}
</script>

<style lang="less" scoped>
.inline {
    display: inline-block;
}

.el-icon-delete {
    color: #f00;
    padding: 5px;
    cursor: pointer;
    border: 1px solid;
    border-radius: 50%;
}
</style>
